<template>
  <view class="container">

    <!-- 入驻说明卡片 -->
    <view class="info-card welcome-card">
      <view class="welcome-header">
        <u-icon name="home" color="#0ea5e9" size="32"></u-icon>
        <text class="welcome-title">欢迎入驻我们的平台</text>
      </view>
      <text class="welcome-desc">请填写以下信息完成商家入驻申请，我们将在1-3个工作日内审核您的申请。</text>
    </view>

    <!-- 基础信息表单 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="info-circle" color="#0ea5e9" size="18"></u-icon>
        <text class="title-text">基础信息</text>
      </view>

      <u--form :model="formData" ref="uForm" :rules="rules" label-width="120px">
        <u-form-item label="商家名称" prop="name" required>
          <u-input v-model="formData.name" placeholder="请输入商家名称" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="联系人" prop="contactPerson" required>
          <u-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="联系电话" prop="phone" required>
          <u-input v-model="formData.phone" placeholder="请输入联系电话" type="number" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="邮箱" prop="email">
          <u-input v-model="formData.email" placeholder="请输入邮箱地址" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="商家分类" prop="category" required>
          <u-input v-model="formData.category" placeholder="请选择商家分类" border="surround" :disabled="true"></u-input>
          <view slot="right" @click="showCategoryPicker">
            <u-icon name="list" label="选择"></u-icon>
          </view>
        </u-form-item>
      </u--form>
    </view>

    <!-- 地址信息表单 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="map" color="#10b981" size="18"></u-icon>
        <text class="title-text">地址信息</text>
      </view>
      <u-form :model="formData" ref="uForm2" label-width="160">
        <u-form-item label="所在省市" prop="location" required>
          <u-input v-model="locationText" placeholder="请选择省市" border="surround" :disabled="true"></u-input>
        </u-form-item>
        <u-form-item label="详细地址" prop="address" required>
          <u-input v-model="formData.address" placeholder="请输入详细地址" border="surround"></u-input>
          <view slot="right" @click="showCategoryPicker">
            <u-icon name="map" label="选择"></u-icon>
          </view>
        </u-form-item>
      </u-form>
    </view>

    <!-- 营业信息表单 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="clock" color="#f59e0b" size="18"></u-icon>
        <text class="title-text">营业信息</text>
      </view>

      <u-form :model="formData" ref="uForm3" label-width="160">
        <u-form-item label="营业时间" prop="businessHours" required>
          <u-input v-model="formData.businessHours" placeholder="例如：10:00 - 22:00" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="人均消费" prop="averageCost">
          <u-input v-model="formData.averageCost" placeholder="请输入人均消费金额" type="number" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="营业执照号" prop="businessLicenseNo" required>
          <u-input v-model="formData.businessLicenseNo" placeholder="请输入营业执照号" border="surround"></u-input>
        </u-form-item>
      </u-form>
    </view>

    <!-- 商家标签 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="tags" color="#ef4444" size="28px"></u-icon>
        <text class="title-text">商家标签</text>
      </view>
      <view class="tags-section">
        <u-tag v-for="tag in availableTags" :key="tag" :text="tag" :type="selectedTags.includes(tag) ? 'primary' : 'info'"
          :plain="!selectedTags.includes(tag)" shape="circle" @click="toggleTag(tag)"></u-tag>
      </view>
    </view>

    <!-- 商家描述 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="file-text" color="#8b5cf6" size="18"></u-icon>
        <text class="title-text">商家描述</text>
      </view>
      <u-textarea v-model="formData.description" placeholder="请简要介绍您的商家特色、服务等信息" :maxlength="200" count height="200"
        :custom-style="textareaStyle"></u-textarea>
    </view>

    <!-- 图片上传 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="camera" color="#06b6d4" size="18"></u-icon>
        <text class="title-text">商家图片</text>
      </view>
      <view class="upload-section">
        <text class="upload-desc">请上传商家Logo和店面图片（最多5张）</text>
        <view class="upload-grid">
          <view class="upload-item" v-for="(image, index) in uploadedImages" :key="index">
            <u-image :src="image" width="200rpx" height="200rpx" border-radius="16rpx" mode="aspectFill"></u-image>
            <view class="delete-btn" @click="deleteImage(index)">
              <u-icon name="close" color="#fff" size="12"></u-icon>
            </view>
          </view>
          <view class="upload-placeholder" v-if="uploadedImages.length < 5" @click="chooseImage">
            <u-icon name="plus" color="#94a3b8" size="32"></u-icon>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action-bar">
      <u-button type="primary" shape="circle" :custom-style="submitBtnStyle" @click="submitApplication" :loading="isSubmitting">
        {{ isSubmitting ? '提交中...' : '提交申请' }}
      </u-button>
    </view>

    <!-- 分类选择器 -->
    <u-picker :show="showCategorySelector" :columns="categoryOptions" @cancel="showCategorySelector =false" @confirm="onCategoryConfirm"></u-picker>

    <!-- 提示组件 -->
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        isSubmitting: false,
        showCategorySelector: false,

        formData: {
          name: '',
          contactPerson: '',
          phone: '',
          email: '',
          category: '',
          province: '',
          city: '',
          address: '',
          businessHours: '',
          averageCost: '',
          businessLicenseNo: '',
          description: ''
        },

        selectedTags: [],
        uploadedImages: [],

        // 表单验证规则
        rules: {
          name: [
            { required: true, message: '请输入商家名称', trigger: 'blur' }
          ],
          contactPerson: [
            { required: true, message: '请输入联系人姓名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
          ],
          email: [
            { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
          ],
          category: [
            { required: true, message: '请选择商家分类', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请输入详细地址', trigger: 'blur' }
          ],
          businessHours: [
            { required: true, message: '请输入营业时间', trigger: 'blur' }
          ],
          businessLicenseNo: [
            { required: true, message: '请输入营业执照号', trigger: 'blur' }
          ]
        },

        // 选项数据
        categoryOptions: [
          { "id": 1, "text": "餐饮" },
          { "id": 2, "text": "购物" },
          { "id": 3, "text": "娱乐" },
          { "id": 4, "text": "服务" },
          { "id": 5, "text": "教育" },
          { "id": 6, "text": "医疗" },
          { "id": 7, "text": "其他" }
        ],
        locationOptions: [
          { name: '北京市', children: [{ name: '朝阳区' }, { name: '海淀区' }, { name: '西城区' }] },
          { name: '上海市', children: [{ name: '浦东新区' }, { name: '黄浦区' }, { name: '徐汇区' }] },
          { name: '广州市', children: [{ name: '天河区' }, { name: '越秀区' }, { name: '海珠区' }] }
        ],
        availableTags: ['推荐', '热门', '新店', '优惠', '老字号', '网红', '特色', '品质', '服务好', '环境佳'],

        // 样式
        inputStyle: {
          backgroundColor: '#f8fafc',
          border: '1rpx solid #e2e8f0',
          borderRadius: '12rpx',
          padding: '0 24rpx'
        },
        textareaStyle: {
          backgroundColor: '#f8fafc',
          border: '1rpx solid #e2e8f0',
          borderRadius: '12rpx',
          padding: '24rpx'
        },
        submitBtnStyle: {
          width: '100%',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none',
          height: '88rpx',
          fontSize: '32rpx'
        }
      }
    },
    computed: {
      locationText() {
        if (this.formData.province && this.formData.city) {
          return `${this.formData.province} ${this.formData.city}`;
        }
        return '';
      }
    },
    onLoad() {
      // 获取系统信息，计算安全区域和导航栏高度
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight;
      this.customNavbarHeight = systemInfo.statusBarHeight + 44;
      this.safeAreaBottom = systemInfo.safeAreaInsets.bottom || 0;
      this.bottomBarHeight = 120 + this.safeAreaBottom;
    },
    methods: {
      // 显示分类选择器
      showCategoryPicker() {
        this.showCategorySelector = true;
      },

      // 分类选择确认
      onCategoryConfirm(e) {
        this.formData.category = this.categoryOptions[e.index];
        this.showCategorySelector = false;
      },
      // 切换标签选择
      toggleTag(tag) {
        const index = this.selectedTags.indexOf(tag);
        if (index > -1) {
          this.selectedTags.splice(index, 1);
        } else {
          if (this.selectedTags.length < 5) {
            this.selectedTags.push(tag);
          } else {
            this.$refs.uToast.show({
              title: '最多只能选择5个标签',
              type: 'warning'
            });
          }
        }
      },

      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 5 - this.uploadedImages.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.uploadedImages = this.uploadedImages.concat(res.tempFilePaths);
          }
        });
      },

      // 删除图片
      deleteImage(index) {
        this.uploadedImages.splice(index, 1);
      },

      // 提交申请
      async submitApplication() {
        try {
          // 表单验证
          const valid = await this.validateForm();
          if (!valid) return;

          this.isSubmitting = true;

          // 构建提交数据
          const submitData = {
            ...this.formData,
            tagsJson: JSON.stringify(this.selectedTags),
            imageUrls: JSON.stringify(this.uploadedImages),
            logo: this.uploadedImages[0] || '', // 第一张图片作为Logo
            rating: 0, // 新商家默认评分
            isEnabled: false, // 待审核状态
            registerTime: new Date().toISOString(),
            createTime: new Date().toISOString()
          };

          console.log('提交数据:', submitData);

          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 2000));

          this.$refs.uToast.show({
            title: '申请提交成功，请等待审核',
            type: 'success'
          });

          // 延迟跳转
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);

        } catch (error) {
          console.error('提交失败:', error);
          this.$refs.uToast.show({
            title: '提交失败，请重试',
            type: 'error'
          });
        } finally {
          this.isSubmitting = false;
        }
      },

      // 表单验证
      async validateForm() {
        try {
          // 基础信息验证
          await this.$refs.uForm.validate();

          // 地址验证
          if (!this.formData.province || !this.formData.city) {
            this.$refs.uToast.show({
              title: '请选择所在省市',
              type: 'warning'
            });
            return false;
          }

          if (!this.formData.address.trim()) {
            this.$refs.uToast.show({
              title: '请输入详细地址',
              type: 'warning'
            });
            return false;
          }

          // 营业信息验证
          if (!this.formData.businessHours.trim()) {
            this.$refs.uToast.show({
              title: '请输入营业时间',
              type: 'warning'
            });
            return false;
          }

          if (!this.formData.businessLicenseNo.trim()) {
            this.$refs.uToast.show({
              title: '请输入营业执照号',
              type: 'warning'
            });
            return false;
          }

          // 图片验证
          if (this.uploadedImages.length === 0) {
            this.$refs.uToast.show({
              title: '请至少上传一张商家图片',
              type: 'warning'
            });
            return false;
          }

          return true;
        } catch (error) {
          console.error('表单验证失败:', error);
          return false;
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background: #f8fafc;
    display: flex;
    flex-direction: column;
  }

  .info-card {
    background: white;
    border-radius: 24rpx;
    margin: 0 10rpx 10rpx;
    padding: 32rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
    border: 1rpx solid #f1f5f9;
  }

  .welcome-card {
    margin-top: 24rpx;

    .welcome-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 16rpx;

      .welcome-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .welcome-desc {
      font-size: 26rpx;
      color: #64748b;
      line-height: 1.5;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    font-size: 28rpx;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 32rpx;
  }

  .tags-section {
    display: flex;
    flex-wrap: wrap;
  }

  .upload-section {
    .upload-desc {
      font-size: 26rpx;
      color: #64748b;
      margin-bottom: 24rpx;
      display: block;
    }

    .upload-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 24rpx;

      .upload-item {
        position: relative;

        .delete-btn {
          position: absolute;
          top: -12rpx;
          right: -12rpx;
          width: 48rpx;
          height: 48rpx;
          background: #ef4444;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4rpx 12rpx rgba(239, 68, 68, 0.3);
        }
      }

      .upload-placeholder {
        width: 200rpx;
        height: 200rpx;
        background: #f8fafc;
        border: 2rpx dashed #cbd5e1;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 12rpx;

        .upload-text {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
    }
  }

  .bottom-action-bar {
    background: white;
    padding: 24rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
    margin-bottom: 100upx;
  }
</style>